// 音效管理工具

// 音效文件路径配置
const AUDIO_FILES = {
  // 鼠标点击音效
  click: '/sounds/click.mp3',
  click2: '/sounds/click2.mp3',
  click3: '/sounds/click3.mp3',
  
  // 悬停音效
  hover: '/sounds/hover.mp3',
  
  // 按钮音效
  button: '/sounds/button.mp3',
  button2: '/sounds/button2.mp3',
  
  // 开关音效
  toggle: '/sounds/toggle.mp3',
  toggle2: '/sounds/toggle2.mp3',
  
  // 通知音效
  notification: '/sounds/notification.mp3'
}

// 音效缓存
const audioCache = new Map()

// 音效设置
const audioSettings = {
  level: 0, // 0=关闭, 1=1档, 2=2档, 3=3档
  volume: 0.5,
  speed: 1.0
}

// 从localStorage加载音效设置
function loadAudioSettings() {
  try {
    const saved = localStorage.getItem('audio-settings')
    if (saved) {
      const settings = JSON.parse(saved)
      Object.assign(audioSettings, settings)
    }
  } catch (error) {
    console.warn('Failed to load audio settings:', error)
  }
}

// 保存音效设置
function saveAudioSettings() {
  try {
    localStorage.setItem('audio-settings', JSON.stringify(audioSettings))
  } catch (error) {
    console.warn('Failed to save audio settings:', error)
  }
}

// 预加载音效文件
function preloadAudio(audioKey) {
  if (audioCache.has(audioKey)) {
    return audioCache.get(audioKey)
  }
  
  const audioPath = AUDIO_FILES[audioKey]
  if (!audioPath) {
    console.warn(`Audio file not found for key: ${audioKey}`)
    return null
  }
  
  const audio = new Audio(audioPath)
  audio.preload = 'auto'
  audio.volume = audioSettings.volume
  audio.playbackRate = audioSettings.speed
  
  audioCache.set(audioKey, audio)
  return audio
}

// 播放音效
export function playAudio(audioKey, options = {}) {
  if (audioSettings.level === 0) {
    return Promise.resolve()
  }
  
  const audio = preloadAudio(audioKey)
  if (!audio) {
    return Promise.resolve()
  }
  
  return new Promise((resolve, reject) => {
    // 克隆音频对象以避免冲突
    const audioClone = audio.cloneNode()
    
    // 应用选项
    if (options.volume !== undefined) {
      audioClone.volume = options.volume
    } else {
      audioClone.volume = audioSettings.volume
    }
    
    if (options.speed !== undefined) {
      audioClone.playbackRate = options.speed
    } else {
      audioClone.playbackRate = audioSettings.speed
    }
    
    // 播放事件处理
    audioClone.addEventListener('ended', () => {
      resolve()
    })
    
    audioClone.addEventListener('error', (error) => {
      reject(error)
    })
    
    // 播放音效
    audioClone.play().catch(error => {
      reject(error)
    })
  })
}

// 音效设置管理
export function setAudioLevel(level) {
  audioSettings.level = Math.max(0, Math.min(3, level))
  saveAudioSettings()
}

export function getAudioLevel() {
  return audioSettings.level
}

export function isAudioEnabled() {
  return audioSettings.level > 0
}

export function setAudioVolume(volume) {
  audioSettings.volume = Math.max(0, Math.min(1, volume))
  saveAudioSettings()
  
  // 更新缓存中的音频音量
  audioCache.forEach(audio => {
    audio.volume = audioSettings.volume
  })
}

export function getAudioVolume() {
  return audioSettings.volume
}

export function setAudioSpeed(speed) {
  audioSettings.speed = Math.max(0.5, Math.min(2.0, speed))
  saveAudioSettings()
  
  // 更新缓存中的音频速度
  audioCache.forEach(audio => {
    audio.playbackRate = audioSettings.speed
  })
}

export function getAudioSpeed() {
  return audioSettings.speed
}

// 获取音效设置
export function getAudioSettings() {
  return { ...audioSettings }
}

// 预加载所有音效
export function preloadAllAudio() {
  Object.keys(AUDIO_FILES).forEach(key => {
    preloadAudio(key)
  })
}

// 清除音效缓存
export function clearAudioCache() {
  audioCache.forEach(audio => {
    audio.pause()
    audio.src = ''
  })
  audioCache.clear()
}

// 生成分级音效
function generateClickSound() {
  try {
    const audioContext = new (window.AudioContext || window.webkitAudioContext)()
    const oscillator = audioContext.createOscillator()
    const gainNode = audioContext.createGain()
    
    oscillator.connect(gainNode)
    gainNode.connect(audioContext.destination)
    
    // 根据档位调整音效
    let frequency, volume, duration
    
    switch (audioSettings.level) {
      case 1: // 1档 - 最轻柔
        frequency = 800
        volume = 0.03
        duration = 0.03
        break
      case 2: // 2档 - 中等
        frequency = 600
        volume = 0.08
        duration = 0.05
        break
      case 3: // 3档 - 较明显
        frequency = 500
        volume = 0.15
        duration = 0.08
        break
      default:
        return Promise.resolve()
    }
    
    oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime)
    oscillator.frequency.exponentialRampToValueAtTime(frequency * 0.8, audioContext.currentTime + duration)
    
    gainNode.gain.setValueAtTime(volume, audioContext.currentTime)
    gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + duration)
    
    oscillator.type = 'sine'
    
    oscillator.start(audioContext.currentTime)
    oscillator.stop(audioContext.currentTime + duration)
    
    return Promise.resolve()
  } catch (error) {
    return Promise.resolve()
  }
}

// 常用音效快捷方法
export const AudioEffects = {
  // 鼠标点击音效（使用生成的音效）
  click: () => generateClickSound(),
  
  // 悬停音效
  hover: () => generateClickSound(),
  
  // 按钮点击音效
  button: () => generateClickSound(),
  
  // 开关音效
  toggle: () => generateClickSound(),
  
  // 通知音效
  notification: () => generateClickSound()
}

// 全局鼠标点击音效监听器
let clickListenerAdded = false

// 添加全局点击音效监听器
export function addGlobalClickAudio() {
  if (clickListenerAdded) return
  
  // 监听所有鼠标点击事件（左键和右键）
  document.addEventListener('mousedown', (event) => {
    // 检查音效是否开启
    if (audioSettings.level === 0) {
      return
    }
    
    // 跳过某些元素
    const target = event.target
    if (target.closest('.no-audio')) {
      return
    }
    
    // 根据鼠标按键播放不同音效
    if (event.button === 0) {
      // 左键点击
      AudioEffects.click()
    } else if (event.button === 2) {
      // 右键点击
      AudioEffects.click()
    }
  }, true)
  
  clickListenerAdded = true
}

// 移除全局点击音效监听器
export function removeGlobalClickAudio() {
  // 注意：由于使用了 addEventListener，这里只是标记
  // 实际应用中可以通过事件委托来控制
  clickListenerAdded = false
}

// 初始化音效系统
export function initAudioSystem() {
  loadAudioSettings()
  preloadAllAudio()
  
  // 添加全局点击音效
  addGlobalClickAudio()
}

// 导出默认配置
export default {
  playAudio,
  setAudioLevel,
  getAudioLevel,
  isAudioEnabled,
  setAudioVolume,
  getAudioVolume,
  setAudioSpeed,
  getAudioSpeed,
  getAudioSettings,
  preloadAllAudio,
  clearAudioCache,
  AudioEffects,
  initAudioSystem
}
